package com.headfirst.BehaviorMode.observer.version1;

import java.util.ArrayList;

/**
 * 具体的主题类，实现了主题接口
 *
 * @author sunhongguang
 * @create 2022-01-18-0:11
 */
public class WeatherData implements Subject {

    // 所有注册的观察者的集合
    private ArrayList<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData() {
        observers = new ArrayList<>();
    }

    /**
     * 将观察者添加到此对象的观察者集中.
     * @param observer an observer to be added.
     * @throws NullPointerException if the parameter observer is null.
     */
    @Override
    public synchronized void registerObserver(Observer observer) {
        if (observer == null)
            throw new NullPointerException();
        if (!observers.contains(observer)) {
            observers.add(observer);
        }
    }

    /**
     * Deletes an observer from the set of observers of this object.
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param observer  the observer to be deleted.
     */
    @Override
    public synchronized void removeObserver(Observer observer) {
        int i = observers.indexOf(observer);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers(){
        observers.clear();
    }

    @Override
    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            Observer observer = observers.get(i);
            observer.update(temperature, humidity, pressure);
        }
    }

    public void measurementsChanged() {
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure) {
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

    /**
     * Returns the number of observers of this <tt>WeatherData_v2</tt> object.
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers(){
        return observers.size();
    }
}
